package com.glsc.ngateway.platform.service.it;

import com.glsc.ngateway.common.api.common.enums.PlatformConstant;
import com.glsc.ngateway.common.api.common.utils.DateUtil;
import com.glsc.ngateway.common.api.platform.dto.it.ParamSearchServerDto;
import com.glsc.ngateway.common.api.platform.dto.it.ServerDeviceExport;
import com.glsc.ngateway.common.api.platform.dto.it.ServerDeviceExportFull;
import com.glsc.ngateway.common.api.platform.dto.user.PlatformUserDto;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.User;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.it.ItApplicationDetail;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.it.ItOperation;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.it.ItServerDevice;
import com.glsc.ngateway.common.base.domain.mysql.gateway.system.SystemMain;
import com.glsc.ngateway.common.base.domainmapper.ServerRowMapper;
import com.glsc.ngateway.common.base.domainmapper.ServerRowMapperFull;
import com.glsc.ngateway.common.base.exception.PlatformException;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.it.ItApplicationDetailRepo;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.it.ItOperationRepo;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.it.ItServerDeviceRepo;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.system.SystemMainRepository;
import com.glsc.ngateway.platform.service.MailService;
import com.glsc.ngateway.platform.service.UserService;
import com.glsc.ngateway.platform.service.costallocation.BusiSystemInfoService;
import com.glsc.ngateway.platform.service.costallocation.IpInfoService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Service
public class ServerService {

    Logger logger = LoggerFactory.getLogger(ServerService.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private BusiSystemInfoService busiSystemInfoService;
    @Autowired
    private UserService userService;
    @Autowired
    private ItServerDeviceRepo itServerDeviceRepo;
    @Autowired
    private ItOperationRepo itOperationRepo;
    @Autowired
    private ItApplicationDetailRepo itApplicationDetailRepo;
    @Autowired
    private MailService mailService;
    @Resource
    private SystemMainRepository systemMainRepository;
    @Resource
    private IpInfoService ipInfoService;


    public ItServerDevice findByDevId(String devId) {
        return itServerDeviceRepo.findByDevId(Integer.parseInt(devId));
    }

    public List<ItServerDevice> queryAllServer() {
        return itServerDeviceRepo.findAll();
    }

    public Page<ItServerDevice> queryServer(Integer page, Integer size, String userId) {
        Pageable pageable = PageRequest.of(page - 1, size);
        Page<ItServerDevice> list = itServerDeviceRepo.getServerDeviceByUser(pageable, userId);
        List<ItServerDevice> flist = list.getContent();
        try {
            List<ItOperation> opList = itOperationRepo.findAll();
            List<ItApplicationDetail> mxList = itApplicationDetailRepo.findAll();
            for (ItServerDevice s : flist) {
                String cc = DateUtil.getStr_yyyyMMdd2(s.getCcTime());
                String wb = DateUtil.getStr_yyyyMMdd2(s.getWbTime());
                String sj = DateUtil.getStr_yyyyMMdd2(s.getSjTime());
                s.setCcTimeStr(cc);
                s.setWbTimeStr(wb);
                s.setSjTimeStr(sj);
                User user = userService.findByUserId(s.getUserId());
                if (user != null) {
                    s.setDepartment(user.getUserDepartment());
                    s.setUserName(user.getName());
                }
                for (ItOperation op : opList) {
                    if (op.getOpId().equals(s.getBusinessName())) {
                        s.setOpStyle(op.getOpStyle());
                        s.setOpStyleName(PlatformConstant.itSystemType.get(op.getOpStyle()));
                        s.setOpName(op.getOpName());
                        break;
                    }
                }
                for (ItApplicationDetail mx : mxList) {
                    if (mx.getMxId().equals(s.getApplicationDetail())) {
                        s.setMxName(mx.getMxName());
                        break;
                    }
                }
            }
        } catch (Exception e) {
            logger.error("queryAllSer异常", e);
        }
        return list;
    }


//    public void add(Map<String, Object> inputMap) {
//        java.util.Date currentTime = new java.util.Date();
//        inputMap.put("insertTime", currentTime);
////		inputMap.put("updateTime", currentTime);
//        // change the camel-naming to underline-naming
//        inputMap = BeanUtil.camel2Underline(inputMap);
//        generalDataManager.insert("t_service_device", inputMap);
//    }
//
//    public void update(Map<String, Object> inputMap) {
//        java.util.Date currentTime = new java.util.Date();
//        inputMap.put("insertTime", currentTime);
////		inputMap.put("updateTime", currentTime);
//        // change the camel-naming to underline-naming
//        inputMap = BeanUtil.camel2Underline(inputMap);
//        generalDataManager.update("t_service_device", inputMap, "dev_id");
//    }

    @Transactional
    public void addOrUpdateServer(ItServerDevice itServerDevice) {
        if (StringUtils.isNotEmpty(itServerDevice.getUserAccount())) {
            PlatformUserDto u = userService.findByUsername(itServerDevice.getUserAccount());
            if (u != null) {
                itServerDevice.setUserId(u.getUserid());
            } else {
                logger.info("未找到云主机责任人");
//                itServerDevice.setUserId(null);
            }
        } else if(StringUtils.isNotBlank(itServerDevice.getUserId())){
            User u = userService.findByUserId(itServerDevice.getUserId());
            if (u == null){
                //增加新用户
                try{
                    userService.addUser(itServerDevice.getUserId());
                }catch (Exception e){
                    e.printStackTrace();
                    mailService.sendMailToAdmin("IT资产OA回调新增用户失败"+itServerDevice.getUserId(),e.getMessage());
                }
            }
//            itServerDevice.setUserId(null);//不设置null，一样保存
        }
        try{
            //第二参数无效
            busiSystemInfoService.synchronizeBusiInfoAddOrUpdate(itServerDevice,false);
        }catch(Exception e){
            logger.info("服务器资产同步异常-新增或编辑", e);
            String message = e.getMessage();
            if(StringUtils.isBlank(message)){
                message =  Arrays.toString(e.getStackTrace());
            }
            mailService.sendMailToAdmin("服务器资产同步系统信息异常-新增或编辑", message);
        }

        Integer devId = itServerDevice.getDevId();
        String addORupdate = "add";
        ItServerDevice oldITserver = new ItServerDevice();
        if(Objects.nonNull(devId)){
            addORupdate = "update";
            ItServerDevice temp = itServerDeviceRepo.findByDevId(devId);
            BeanUtils.copyProperties(temp,oldITserver);
        }
        ItServerDevice saved = itServerDeviceRepo.save(itServerDevice);
        try{
            ipInfoService.synchronizeBaseIpInfoAddOrUpdate(saved,oldITserver,addORupdate);
        }catch(Exception e){
            logger.info("服务器资产同步异常-新增或编辑", e);
            String message = e.getMessage();
            if(StringUtils.isBlank(message)){
                message =  Arrays.toString(e.getStackTrace());
            }
            mailService.sendMailToAdmin("服务器资产同步IP异常-新增或编辑", message);
        }
    }

    public void deleteServer(String devId) {
        ItServerDevice it = itServerDeviceRepo.findByDevId(Integer.parseInt(devId));
        if (it != null) {
            try {
                busiSystemInfoService.syncItServerDeviceDelete(devId);
            } catch (Exception e) {
                logger.info("服务器资产同步异常-删除", e);
                String message = e.getMessage();
                if(StringUtils.isBlank(message)){
                    message =  Arrays.toString(e.getStackTrace());
                }
                mailService.sendMailToAdmin("服务器资产同步异常-删除", message);
            }
            try {
                ipInfoService.doOfflineIP(devId);
            } catch (Exception e) {
                logger.info("物理机同步删除异常-删除", e);
                String message = e.getMessage();
                if(StringUtils.isBlank(message)){
                    message =  Arrays.toString(e.getStackTrace());
                }
                mailService.sendMailToAdmin("物理机同步删除异常-删除",message);
            }
            itServerDeviceRepo.delete(it);
        }
    }

    //物理服务器数据导出
    public List<ServerDeviceExport> queryServerOutPut() {
//        String condition = "";
//        if (ssd != null) {
//            condition += " and sn like '%" + ssd + "%' or ip1 like '%" + ssd + "%'or ip2 like '%" + ssd + "%' or mac1 like '%" + ssd + "%' or mac2 like '%" + ssd + "%' or ilo like '%" + ssd + "%' ";
//        }
//		if(machine!=null) {
//			condition+=" and machine="+machine;
//		}
        String sql = "select b.op_name business_name, " +
                "(select dict_value from t_it_dict d where d.zd_id = a.network_segment) network_segment, " +
                "mx_name application_detail, " +
                "(select dict_value from t_it_dict e where e.zd_id = a.machine_room) machine_room, " +
                "machine_cab,machine_unit, capital_type, " +
                "capital_typed, " +
                "(select dict_value from t_it_dict g where g.zd_id = a.brand) brand, " +
                "(select dict_value from t_it_dict h where h.zd_id = a.capital_style) capital_style, " +
                "brand_type, " +
                "ip1,ip2,sn, " +
                "(select dict_value from t_it_dict j where j.zd_id = a.operation_sys) operation_sys, " +
                "ilo,cc_time,wb_time, " +
                "(select dict_value from t_it_dict k where k.zd_id = a.machine_status) machine_status, " +
                "name, " +
                "department," +
                "sj_time " +
                "from t_it_server_device a " +
                "left join t_gw_system_main b on a.business_name = b.system_class_no " +
                "left join t_it_application_detail c on a.application_detail = c.mx_id " +
                "left join t_user d on a.user_id = d.userid where 1=1 ";
        return jdbcTemplate.query(sql, new ServerRowMapper());
    }


    //物理服务器数据全部导出
    public List<ServerDeviceExportFull> queryServerFullOutPut() {
//        String condition = "";
//        if (ssd != null) {
//            condition += " and sn like '%" + ssd + "%' or ip1 like '%" + ssd + "%'or ip2 like '%" + ssd + "%' or mac1 like '%" + ssd + "%' or mac2 like '%" + ssd + "%' or ilo like '%" + ssd + "%' ";
//        }
//		if(machine!=null) {
//			condition+=" and machine="+machine;
//		}
        String sql = "select a.dev_id dev_id, b.op_name business_name, " +
                "(select dict_value from t_it_dict d where d.zd_id = a.network_segment) network_segment, " +
                "mx_name application_detail, " +
                "(select dict_value from t_it_dict e where e.zd_id = a.machine_room) machine_room, " +
                "machine_cab,machine_unit, capital_type, " +
                "capital_typed, " +
                "(select dict_value from t_it_dict g where g.zd_id = a.brand) brand, " +
                "(select dict_value from t_it_dict h where h.zd_id = a.capital_style) capital_style, " +
                "brand_type, " +
                "ip1,ip2,sn, " +
                "(select dict_value from t_it_dict j where j.zd_id = a.operation_sys) operation_sys, " +
                "ilo,cc_time,wb_time, " +
                "(select dict_value from t_it_dict k where k.zd_id = a.machine_status) machine_status, " +
                "name, " +
                "department, " +
                "sj_time,pn_pid,cpu,memory,plan_on, " +
                "case when support_power=0 then '空' when support_power=1 then '单电源' when support_power=2 then '双电源' end support_power, " +
                "bz,mac1,mac2,mac3,mac4,mac5,mac6,mac7,mac8,mac9,mac10,mac11,mac12, " +
                "ip3,ip4,qj,fix_record,fix_time,bf " +
                "from t_it_server_device a " +
                "left join t_gw_system_main b on a.business_name = b.system_class_no " +
                "left join t_it_application_detail c on a.application_detail = c.mx_id " +
                "left join t_user d on a.user_id = d.userid where 1=1 ";
        return jdbcTemplate.query(sql, new ServerRowMapperFull());
    }


    //搜索服务器
    public List<ItServerDevice> searchDevice(String ssd,boolean isLike) {

//      String sql = "select a.*,b.department from t_it_server_device a left join t_admin_user b on b.user_id=a.user_id where sn like '%" + ssd + "%' "
//                + "or ip1 like '%" + ssd + "%' or ip2 like '%" + ssd + "%' "
//                + "or mac1 like '%" + ssd + "%' or mac2 like '%" + ssd + "%' or ilo like '%" + ssd + "%' ";
        if (isLike){
            return itServerDeviceRepo.searchDevice(ssd);
        } else {
            return itServerDeviceRepo.searchDeviceNotLike(ssd);
        }

    }
//
//    //搜索服务器名称
//    public List multiSearchDevice(Map<String, Object> serverDeviceList) {
//        String condition = " left join t_admin_user c on c.user_id =a.user_id where  1=1 ";
//        String businessName = (String) serverDeviceList.get("businessName");
//        if (!"".equals(businessName) && businessName != null) {
//            condition += " and business_name = '" + businessName + "'";
//        }
//        String applicationDetail = (String) serverDeviceList.get("applicationDetail");
//        if (!"".equals(applicationDetail) && applicationDetail != null) {
//            condition += " and application_detail = '" + applicationDetail + "'";
//        }
//        String capitalType = (String) serverDeviceList.get("capitalType");
//        if (!"".equals(capitalType) && capitalType != null) {
//            condition += " and capital_type = '" + capitalType + "'";
//        }
//        String capitalTyped = (String) serverDeviceList.get("capitalTyped");
//        if (!"".equals(capitalTyped) && capitalTyped != null) {
//            condition += " and capital_typed like '%" + capitalTyped + "%'";
//        }
//        String ip1 = (String) serverDeviceList.get("ip1");
//        if (!"".equals(ip1) && ip1 != null) {
//            condition += " and ip1 = '" + ip1 + "'";
//        }
//        String ip2 = (String) serverDeviceList.get("ip2");
//        if (!"".equals(ip2) && ip2 != null) {
//            condition += " and ip2 = '" + ip2 + "'";
//        }
//        String sn = (String) serverDeviceList.get("sn");
//        if (!"".equals(sn) && sn != null) {
//            condition += " and sn like '%" + sn + "%'";
//        }
//        Integer machineRoom = (Integer) serverDeviceList.get("machineRoom");
//        if (machineRoom != null) {
//            condition += " and machine_room = " + machineRoom.intValue();
//        }
//        String machineCab = (String) serverDeviceList.get("machineCab");
//        if (!"".equals(machineCab) && machineCab != null) {
//            condition += " and machine_cab like '%" + machineCab + "%'";
//        }
//        Integer operationSys = (Integer) serverDeviceList.get("operationSys");
//        if (operationSys != null) {
//            condition += " and operation_sys = " + operationSys.intValue();
//        }
//        Integer capitalStyle = (Integer) serverDeviceList.get("capitalStyle");
//        if (capitalStyle != null) {
//            condition += " and capital_style = " + capitalStyle.intValue();
//        }
//        Integer machineStatus = (Integer) serverDeviceList.get("machineStatus");
//        if (machineStatus != null) {
//            condition += " and machine_status = " + machineStatus.intValue();
//        }
//        Integer networkSegment = (Integer) serverDeviceList.get("networkSegment");
//        if (networkSegment != null) {
//            condition += " and network_segment = " + networkSegment.intValue();
//        }
//        Integer opStyle = (Integer) serverDeviceList.get("opStyle");
//        if (opStyle != null) {
//            condition += " and op_style = " + opStyle.intValue();
//        }
//        String userId = (String) serverDeviceList.get("userId");
//        if (!"".equals(userId) && userId != null) {
//            condition += " and a.user_id = '" + userId + "'";
//        }
////		String sql = "select * from t_service_device  "+condition;
//        String sql = "select a.*,b.op_style,c.department from t_service_device a left join t_operation b on a.business_name = b.op_id" + condition;
//        return BeanUtil.underline2Camel(jdbcTemplate.queryForList(sql));
//    }
//
//


    //搜索服务器
    public Page<ItServerDevice> searchServer(Integer page, Integer size,
                                             String businessName, String applicationDetail, String opStyle, String machineRoom,
                                             String machineCab, String capitalTyped, String capitalType, String capitalStyle,
                                             String ip1, String ip2, String sn, String operationSys, String userId, String machineStatus, ParamSearchServerDto params) {
        Pageable pageable = PageRequest.of(page - 1, size);

        if (StringUtils.isEmpty(params.getSearchMacParam())){
            params.setSearchMacParam(null);
        }
        if (StringUtils.isEmpty(params.getSearchIpParam())){
            params.setSearchIpParam(null);
        }
        String devId = params.getDevId();
        Integer querydevId = null;
        if (StringUtils.isEmpty(devId)){
            params.setDevId(null);
        }else{
            try {
                querydevId = Integer.valueOf(devId);
            } catch (Exception e) {
                logger.info("不能转化为整型，{}",devId);
                throw PlatformException.errorWithOutMail("请输入整数类型");
            }
        }


        Page<ItServerDevice> list = itServerDeviceRepo.searchServerDevice(businessName, applicationDetail, opStyle, machineRoom,
                machineCab, capitalTyped, capitalType, capitalStyle, ip1, ip2, sn, operationSys, userId, machineStatus,params.getSearchMacParam(),params.getSearchIpParam(),pageable,querydevId);
        List<ItServerDevice> flist = list.getContent();
        try {
            List<SystemMain> opList = systemMainRepository.findAll();
            List<ItApplicationDetail> mxList = itApplicationDetailRepo.findAll();
            for (ItServerDevice s : flist) {
                String cc = DateUtil.getStr_yyyyMMdd2(s.getCcTime());
                String wb = DateUtil.getStr_yyyyMMdd2(s.getWbTime());
                String sj = DateUtil.getStr_yyyyMMdd2(s.getSjTime());
                String fix = DateUtil.getStr_yyyyMMdd2(s.getFixTime());
                s.setCcTimeStr(cc);
                s.setWbTimeStr(wb);
                s.setSjTimeStr(sj);
                s.setFixTimeStr(fix);
                List<String> ipList = new ArrayList<>();
                if(StringUtils.isNotBlank(s.getIp1())){
                    ipList.add(s.getIp1());
                }
                if(StringUtils.isNotBlank(s.getIp2())){
                    ipList.add(s.getIp2());
                }
                if(StringUtils.isNotBlank(s.getIp3())){
                    ipList.add(s.getIp3());
                }
                if(StringUtils.isNotBlank(s.getIp4())){
                    ipList.add(s.getIp4());
                }
                s.setIpList(ipList);
                if (StringUtils.isNotEmpty(s.getUserId())) {
                    User user = userService.findByUserId(s.getUserId());
                    if (user != null) {
                        s.setDepartment(user.getUserDepartment());
                        s.setUserName(user.getName());
                        s.setUserAccount(user.getUsername());
                    }
                }
                for (SystemMain op : opList) {
                    if (op.getSystemClassNo().equals(s.getBusinessName())) {
                        s.setOpStyle(op.getMainClass());
//                        s.setOpStyleName(PlatformConstant.itSystemType.get(op.getOpStyle()));
                        s.setOpName(op.getOpName());
                        break;
                    }
                }
                for (ItApplicationDetail mx : mxList) {
                    if (mx.getMxId().equals(s.getApplicationDetail())) {
                        s.setMxName(mx.getMxName());
                        break;
                    }
                }
            }
        } catch (Exception e) {
            logger.error("searchServer搜索异常", e);
        }
        return list;
    }
}
